<?php

namespace hichefu;

use think\Exception;

/**
 * Aes加密解密类
 **/
class Aes
{

    protected $key;

    public function __construct()
    {
        $config = config('driving.hichefu');
        $this->key = $config['appSecret'];
    }

    public function encrypt($input)
    {
        $ivSize = openssl_cipher_iv_length('aes-128-ecb');
        $iv = $ivSize > 0 ? openssl_random_pseudo_bytes($ivSize) : ''; // 注意：ECB模式不需要IV，但某些PHP版本可能需要一个空的IV
        $encrypted = openssl_encrypt($input, 'aes-128-ecb', $this->key, OPENSSL_RAW_DATA, $iv);
        if ($encrypted === false) {
            throw new Exception('encrypt error: ' . openssl_error_string());
        }
        return base64_encode($encrypted);
    }

    public function decrypt($input)
    {
        $ivSize = openssl_cipher_iv_length('aes-128-ecb');
        $iv = $ivSize > 0 ? openssl_random_pseudo_bytes($ivSize) : ''; // 注意：ECB模式不需要IV，但某些PHP版本可能需要一个空的IV
        $decrypted = openssl_decrypt(base64_decode($input), 'aes-128-ecb', $this->key, OPENSSL_RAW_DATA, $iv);
        if ($decrypted === false) {
            throw new Exception('decrypt error: ' . openssl_error_string());
        }
        return $decrypted;
    }

}
